package cn.hdu.liang.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelTest {
    public static void main(String[] args) {
        try(ServerSocketChannel ssc = ServerSocketChannel.open()) {

            ssc.configureBlocking(false);
            ssc.socket().bind(new InetSocketAddress(8888));
            ByteBuffer buffer = ByteBuffer.allocate(48);

            while(true) {
                SocketChannel socketChannel = ssc.accept();
                if(socketChannel != null) {
                    int bytesRead = socketChannel.read(buffer);
                    while(bytesRead != -1) {
                        buffer.flip();
                        while(buffer.hasRemaining()) {
                            System.out.print((char) buffer.get());
                        }
                        System.out.println();
                        buffer.clear();
                        bytesRead = socketChannel.read(buffer);
                    }
                }
            }
        } catch(IOException e) {
            e.printStackTrace();
        }

    }
}
